package org.microdream.easy.deploy.action;

import ice.server.comm.BaseAction;
import ice.server.comm.ParamBulider;
import ice.tool.ResultMap;
import ice.tool.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.microdream.easy.deploy.po.DUser;
import org.microdream.easy.deploy.po.DUserOrg;
import org.microdream.easy.deploy.service.DUserOrgService;
import org.microdream.easy.deploy.service.DUserService;
import org.microdream.easy.deploy.utils.ListUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("DUser")
public class DUserAction extends BaseAction {

    @Resource
    private DUserService dUserService;
    @Resource
    private DUserOrgService dUserOrgService;

    @PostMapping("/searchByPage")
    public Map searchByPage(Integer limit, Integer offset){
        if(limit==null || offset==null){
            return null;
        }
        return dUserService.searchByPage(ParamBulider.build().addEqual("rows", limit).addEqual("page", offset / limit).addEqual("isDelete",0).get());
    }

    @PostMapping("")
    public Map add(DUser dUser,String orgCode){
        dUser.setIsLock(0);
        dUser.setIsDelete(0);
        dUser.setCreateTime(new Timestamp(System.currentTimeMillis()));
        dUser.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        return dUserService.add(dUser,orgCode);
    }

    @PutMapping("")
    public Map update(DUser dUser,String orgCode){
        DUser dUserOld = dUserService.get(dUser.getId());
        try {
            BeanUtil.copyNotEmptyProprties(dUser,dUserOld);
            dUserOld.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        } catch (Exception e) {
            return ResultMap.build().warningState().message(e.getMessage()).get();
        }
        return dUserService.upd(dUserOld,orgCode);
    }

    @DeleteMapping("/{key}")
    public Map delete(@PathVariable("key")String key){
        if(StringUtils.isEmpty(key)){
            return ResultMap.build().warningState().message("无效数据").get();
        }
        List<String> ids = Arrays.asList(key.split(","));
        return dUserService.del(ListUtil.StringToInteger(ids));
    }

    @GetMapping("/{key}")
    public DUser searchById(@PathVariable("key") Integer key){
        DUser dUser = dUserService.get(key);
        DUserOrg dUserOrg = dUserOrgService.findSingle(ParamBulider.build().addEqual("userAccount",dUser.getUserAccount()).get());
        if(StringUtils.isNotEmpty(dUserOrg.getOrgCode())){
            dUser.set("orgCode",dUserOrg.getOrgCode());
        }
        return dUser;
    }

    @GetMapping("/lock/{key}")
    public Map lock(@PathVariable("key")Integer key){
        return dUserService.lock(key);
    }
}
